package com.example.service;

import cn.hutool.core.collection.CollectionUtil;
import com.example.dao.ZuoyeInfoDao;
import com.example.entity.Account;
import com.example.entity.ZuoyeInfo;
import com.example.vo.ZuoyeInfoVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class ZuoyeInfoService {

    @Resource
    private ZuoyeInfoDao zuoyeInfoDao;

    public ZuoyeInfo add(ZuoyeInfo info) {
    zuoyeInfoDao.insertSelective(info);
        return info;
    }

    public void delete(Long id) {
        zuoyeInfoDao.deleteByPrimaryKey(id);
    }

    public void update(ZuoyeInfo info) {
        zuoyeInfoDao.updateByPrimaryKeySelective(info);
    }

    public ZuoyeInfo findById(Long id) {
        return zuoyeInfoDao.selectByPrimaryKey(id);
    }

    public ZuoyeInfo findByReserveId(Long id, Long parentId) {
        List<ZuoyeInfoVo> list = zuoyeInfoDao.findByReserveId(id, parentId);
        if (CollectionUtil.isEmpty(list)) {
            return null;
        } else {
            return list.get(0);
        }
    }

    public PageInfo<ZuoyeInfoVo> findPage(Integer pageNum, Integer pageSize, Integer flag, HttpServletRequest request) {
        Account account = (Account) request.getSession().getAttribute("user");
        if (account == null) {
            return PageInfo.of(new ArrayList<>());
        }
        Integer level = account.getLevel();
        PageHelper.startPage(pageNum, pageSize);
        List<ZuoyeInfoVo> info;
        if (1 == flag) {
            info = (1 == level) ? zuoyeInfoDao.findByPublishId(0L) : zuoyeInfoDao.findByPublishId(account.getId());
        } else {
            info = (1 == level || 2 == level) ? zuoyeInfoDao.findByReserveId(0L, null) : zuoyeInfoDao.findByReserveId(account.getId(), null);
        }
        return PageInfo.of(info);
    }

    public PageInfo<ZuoyeInfoVo> findPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ZuoyeInfoVo> info = zuoyeInfoDao.findAllReserve();
        return PageInfo.of(info);
    }

    public List<ZuoyeInfoVo> findAll() {
        return zuoyeInfoDao.findAllReserve();
    }
}
